package 力扣_树算法.遍历;

import java.util.*;

/**590. N 叉树的后序遍历
 * @author zx
 * @create 2022-04-18 21:28
 */
public class N叉树的后续遍历_590 {
    public List<Integer> postorder2(Node root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Deque<Node> stack = new ArrayDeque<Node>();
        Set<Node> visited = new HashSet<Node>();
        stack.push(root);
        while (!stack.isEmpty()) {
            Node node = stack.peek();
            /* 如果当前节点为叶子节点或者当前节点的子节点已经遍历过 */
            if (node.children.size() == 0 || visited.contains(node)) {
                stack.pop();
                res.add(node.val);
                continue;
            }
            for (int i = node.children.size() - 1; i >= 0; --i) {
                stack.push(node.children.get(i));
            }
            visited.add(node);
        }
        return res;
    }

    /**
     * @return 递归
     */
    public List<Integer> postorder(Node root) {
        List<Integer> res = new ArrayList<>();
        helper(root,res);
        return res;
    }
    private void helper(Node root,List<Integer> list){
        if(root == null){
            return;
        }
        for(Node node : root.children){
            helper(node,list);
        }
        list.add(root.val);
    }
}
